<template>
	<uni-popup ref="popup_control_play" type="bottom" border-radius="16px 16px 0 0">
		<view class="pop-box pad-20">
			<view class="flex flex-between flex-center">
				<view class="col-000-8 font-18 font-600">
					{{ $t('userinfo.editProfile') }}
				</view>
				<view class="close" @click="closePopup">
					<uni-icons type="closeempty" color="rgba(0,0,0,0.4)" size="20"></uni-icons>
				</view>
			</view>
			<view class="m-t-20">
				<view class="avatar">
					<uni-id-pages-avatar width="144rpx" height="144rpx"></uni-id-pages-avatar>
				</view>
				<view class="font-12 col-000-8 text-center m-t-4">
					{{ $t('userinfo.changeAvatar') }}
				</view>
				<view class="m-t-20">
					<view class="font-14 col-000-8 font-500">
						{{ $t('userinfo.username') }}
					</view>
					<view class="m-t-8">
						<uni-easyinput class="input-box" :inputBorder="false" v-model="userInfo.username" :placeholder="$t('userinfo.usernamePlaceholder')"
							trim="all" @blur="validateUsername" />
					</view>
					<view v-if="usernameError" class="error-msg font-12 col-red m-t-4">
						{{ $t('userinfo.usernameFormatError') }}
					</view>
				</view>
				<view class="m-t-20">
					<view class="font-14 col-000-8 font-500">
						{{ $t('userinfo.nickname') }}
					</view>
					<view class="m-t-8">
						<uni-easyinput class="input-box" :inputBorder="false" v-model="userInfo.nickname" :placeholder="$t('userinfo.nicknamePlaceholder')"
							trim="all" />
					</view>
				</view>
				<view class="send-btn font-14 col-fff font-500 m-t-20 flex-center-center" @click="saveProfile()">
					{{ $t('userinfo.save') }}
				</view>
			</view>
		</view>
	</uni-popup>
</template>

<script>
	const uniIdCo = uniCloud.importObject("uni-id-co")
	import {
		store,
		mutations
	} from '@/uni_modules/uni-id-pages/common/store.js'
	export default {
		data() {
			return {
				univerifyStyle: {
					authButton: {
						"title": "本机号码一键绑定", // 授权按钮文案
					},
					otherLoginButton: {
						"title": "其他号码绑定",
					}
				},
				userInfo: {
					username: '',
					nickname: '',
				},
				hasPwd: false,
				showLoginManage: false, //通过页面传参隐藏登录&退出登录按钮
				setNicknameIng: false,
				usernameError: false // 用户名格式错误标记
			}
		},
		methods: {
			open() {
				this.$refs.popup_control_play.open('bottom');
				this.loadUserInfo()
			},
			closePopup() {
				// 延迟显示 TabBar，确保弹窗关闭动画完成
				setTimeout(() => {
					uni.showTabBar({
						animation: true
					});
				}, 300);
				this.$refs.popup_control_play.close();
				// 触发父页面刷新
				this.$emit('refresh')
			},
			// 验证用户名格式(仅允许英文和数字)
			validateUsername() {
				const username = this.userInfo.username || '';
				// 仅允许英文字母和数字
				const regex = /^[a-zA-Z0-9]*$/;
				this.usernameError = username.length > 0 && !regex.test(username);
			},
			// 加载用户信息
			async loadUserInfo() {
				try {
					try {
						// 回退到本地存储的用户信息
						let userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
						console.log(userInfo)
						this.userInfo = {
							...userInfo,
							id: userInfo._id,
							name: userInfo.nickname || userInfo.username || '未设置昵称'
						};

					} catch (e) {
						console.error('获取最新用户信息失败，使用本地存储:', e);
						// 回退到本地存储的用户信息
						let userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
						this.userInfo = {
							...userInfo,
							id: userInfo._id,
							name: userInfo.nickname || userInfo.username || '未设置昵称'
						};
					}
				} catch (error) {
					console.error('加载用户信息失败:', error);
					uni.showToast({
						title: this.$t('userinfo.loadUserInfoFailed'),
						icon: 'none'
					});
				}
			},
			// 保存个人资料
			async saveProfile() {
				try {
					// 验证用户名格式
					this.validateUsername();
					if (this.usernameError) {
						uni.showToast({
							title: this.$t('userinfo.usernameFormatError'),
							icon: 'none',
							duration: 2000
						});
						return;
					}
					
					uni.showLoading({
						title: this.$t('userinfo.saving'),
						mask: true
					});
					
					const userInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
					console.log('当前用户信息:', userInfo)
					
					// 确保有用户ID
					if (!userInfo._id) {
						throw new Error(this.$t('userinfo.userNotFound'));
					}

					// 准备更新数据 - uid 和 username 是必填参数
					const updateData = {
						uid: userInfo._id,
						username: this.userInfo.username || userInfo.username || '',
						nickname: this.userInfo.nickname || '',
					};

					console.log('准备更新的数据:', updateData);

					// 使用uni-id-co云对象更新用户资料（禁用自动错误提示）
					const uniIdCo = uniCloud.importObject("uni-id-co", {
						customUI: true  // 禁用自动错误提示
					});
					
					let result;
					try {
						// 调用云对象更新用户信息
						
						console.log('调用云对象更新用户信息:', updateData);
						result = await uniIdCo.updateUser(updateData);
					} catch (e) {
						// 捕获 uni-id-co 抛出的错误，防止弹窗
						console.error('uni-id-co updateUser 错误:', e);
						
						// 检查是否是用户名重复错误
						if (e.message && e.message.includes('E11000') && e.message.includes('username')) {
							result = {
								errCode: 'USERNAME_EXISTS',
								errMsg: this.$t('userinfo.usernameExists')
							};
						} else {
							// 其他错误
							result = {
								errCode: 'UPDATE_FAILED',
								errMsg: e.message || this.$t('userinfo.saveFailed')
							};
						}
					}

					uni.hideLoading();

					// 输出完整结果,便于调试
					console.log('更新用户信息结果:', result);

					if (result.errCode === 0) {
						// 更新成功
						const storageUserInfo = uni.getStorageSync('uni-id-pages-userInfo') || {};
						const newUserInfo = {
							...storageUserInfo,
							username: updateData.username,
							nickname: updateData.nickname
						};

						// 使用 setUserInfo 直接更新本地状态,不再调用数据库
						// 因为云函数已经更新过数据库了
						mutations.setUserInfo(newUserInfo);

						uni.showToast({
							title: this.$t('userinfo.saveSuccess'),
							icon: 'success'
						});

						// 延迟关闭弹窗,确保数据已更新
						setTimeout(() => {
							this.closePopup();
						}, 800);
						
					} else {
						// 更新失败
						console.error('更新用户失败, 详细信息:', result);
						
						uni.hideLoading();
						
						// 处理特定错误码
						let errorMsg = result.errMsg;
						if (result.errCode === 'USERNAME_EXISTS') {
							errorMsg = this.$t('userinfo.usernameExists');
						} else if (result.errCode === 'INVALID_USERNAME') {
							errorMsg = this.$t('userinfo.usernameFormatError') || '用户名格式不正确';
						}
						
						uni.showToast({
							title: errorMsg || this.$t('userinfo.saveFailed'),
							icon: 'none',
							duration: 3000
						});
					}
				} catch (error) {
					// 增强错误日志
					console.error('保存个人资料失败:', error);
					
					uni.hideLoading();
					
					let errorMsg = this.$t('userinfo.saveFailed');
					
					// 处理数据库唯一索引冲突错误（E11000）
					if (error.message && error.message.includes('E11000')) {
						if (error.message.includes('username')) {
							errorMsg = this.$t('userinfo.usernameExists');
						}
					} 
					// 处理云函数返回的错误
					else if (error.errMsg) {
						errorMsg = error.errMsg;
					} 
					// 处理普通Error对象
					else if (error.message) {
						// 检查是否是特定的错误消息
						if (error.message.includes('已被使用') || error.message.includes('usernameExists')) {
							errorMsg = this.$t('userinfo.usernameExists');
						} else {
							errorMsg = error.message;
						}
					}
					
					uni.showToast({
						title: errorMsg,
						icon: 'none',
						duration: 3000
					});
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.pop-box {
		width: 100%;
		background-color: #F3F3F3;
		border-top-left-radius: 32rpx;
		border-top-right-radius: 32rpx;

		.input-box {
			width: 99%;
			border-radius: 8rpx;
			border: 2rpx solid rgba(0, 0, 0, 0.8);
			overflow: hidden;
		}

		.send-btn {
			width: 100%;
			height: 100rpx;
			background: #000000;
			border-radius: 16rpx;
		}
		
		.error-msg {
			color: #ff0000;
		}
	}

	.avatar {
		width: 144rpx;
		height: 144rpx;
		overflow: hidden;
		border-radius: 100%;
		margin: 0 auto;
	}
	
	.col-red {
		color: #ff0000;
	}
</style>